import json

from flask import Blueprint, request, jsonify

from web.model.Agent import Agent, agentSchema
from web.model.Classify import classifySchema, Classify
from web.model.Result import Result
from web.model.User import User, userSchema
from web.service.Service import Service

bp = Blueprint('main', __name__)

service = Service()

@bp.get("/hello")
def home():
    return "Hello World!"

@bp.post("/login")
def login():
    print(json.dumps(request.args)) # 获取post请求的表单参数
    username = request.args['username']
    password = request.args['password']

    user = service.login(username, password)
    print(user)
    if user is None:
        return jsonify(Result.error("用户名或密码错误"))
    else:
        return jsonify(Result.success(userSchema.dumps(user),"用户登录成功")) # 返回json

@bp.get("/checkUsername")
def checkUsername():
    username = request.args['username']
    flag = service.selectUsername(username)
    print(flag)
    if flag:
        return jsonify(Result.error("账号已存在"))
    else:
        return jsonify(Result.success(None,"账号不存在"))

@bp.post("/reg")
def reg():
    print(json.dumps(request.json)) # 获取post请求的表单参数
    print(json.dumps(request.args)) # 获取post请求的表单参数
    user = request.json
    user = User(**user)
    print(type(user))
    print(user.username)
    flag = service.reg(user)
    if flag:
        return jsonify(Result.success(None,"用户注册成功"))
    else:
        return jsonify(Result.error("用户注册失败"))


@bp.get("/classify")
def getClassify():
    classifyes = service.selectClassify()
    return jsonify(Result.success(classifySchema.dumps(classifyes,many=True),"查询成功"))

@bp.post("/addclassify")
def addClassify():
    classify = request.json
    classify = Classify(**classify)
    flag = service.addClassify(classify)
    if flag:
        return jsonify(Result.success(None, "分类添加成功"))
    else:
        return jsonify(Result.error("分类添加失败"))

@bp.get("/agents")
def getAgents():
    classify_id = request.args.get("classify_id",default=None)
    keyword = request.args.get("keyword",default=None)
    agent = service.selectAgent(classify_id, keyword)
    return jsonify(Result.success(agentSchema.dumps(agent,many=True), "查询成功"))

@bp.post("/addAgent")
def addAgent():
    agentJson = request.json
    print(agentJson)
    agent = Agent()
    agent.name = agentJson['name']
    agent.url = agentJson['url']
    agent.images = agentJson['images']
    agent.descs = agentJson['descs']
    # agent.classify = Classify()
    # agent.classify.id = agentJson['classify']['id']
    agent.classify_id = agentJson['classify']['id']
    # agent.classify_id = agentJson.classify.id
    flag = service.addAgent(agent)
    if flag:
        return jsonify(Result.success(None, "智能体添加成功"))
    else:
        return jsonify(Result.error("智能体添加失败"))
